<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="分享类型" prop="type">
        <el-select v-model="queryParams.type" placeholder="请选择分享类型" clearable>
          <el-option v-for="dict in dict.type.share_type" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="时长类型" prop="timeType">
        <el-select v-model="queryParams.timeType" placeholder="请选择时长类型" clearable>
          <el-option v-for="dict in dict.type.time_limit" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="审批状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择审批状态" clearable>
          <el-option v-for="dict in dict.type.apply_status" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5" v-if="false">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['filemgr:sharemgr:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['filemgr:sharemgr:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['filemgr:sharemgr:remove']">删除</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="sharemgrList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="主键" align="center" width="55" prop="id" />
      <el-table-column label="谁分享的名字" align="center" prop="shareUserName" />
      <el-table-column label="分享类型" align="center" prop="type">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.share_type" :value="scope.row.type" />
        </template>
      </el-table-column>
      <el-table-column label="分享给谁名字" align="center" prop="userName" />
      <el-table-column label="文件" align="center" prop="filemgr.name" />
      <el-table-column label="时长类型" align="center" prop="timeType">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.time_limit" :value="scope.row.timeType" />
        </template>
      </el-table-column>
      <el-table-column label="时限" align="center" prop="deadline" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.deadline, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <el-table-column label="审批人" align="center" prop="applyUserName" />
      <el-table-column label="审批状态" align="center" prop="status">
        <template slot-scope="scope">
          <span>
            <dict-tag :options="dict.type.apply_status" :value="scope.row.status" />
          </span>
        </template>
      </el-table-column>
      <el-table-column label="备注信息" align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-download"
            @click="resource(scope.row.filemgr.name)">下载</el-button>
          <el-button size="mini" type="text" icon="el-icon-download" @click="handleUpdate(scope.row)">审批</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改分享管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="分享类型" prop="type">
          <el-radio-group v-model="form.type">
            <el-radio v-for="dict in dict.type.share_type" :key="dict.value" :label="dict.value" :disabled="true">{{
              dict.label
            }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="分享给谁" prop="userId" v-if="form.type == 2">
          <el-select v-model="form.userId" placeholder="请选择分享的人" :disabled="true">
            <el-option v-for="item in userList" :key="item.userId" :label="item.userName"
              :value="item.userId"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="时长类型" prop="timeType">
          <el-radio-group v-model="form.timeType">
            <el-radio v-for="dict in dict.type.time_limit" :key="dict.value" :label="dict.value" :disabled="true">{{
              dict.label
            }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="时限" prop="deadline" v-if="form.timeType == 2">
          <el-date-picker clearable v-model="form.deadline" type="date" value-format="yyyy-MM-dd" :disabled="true"
            placeholder="请选择时限">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="审批状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio v-for="dict in getDict(dict.type.apply_status)" :key="dict.value" :label="dict.value">{{ dict.label
            }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注信息" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listSharemgr,
  getSharemgr,
  delSharemgr,
  addSharemgr,
  updateSharemgr,
} from "@/api/filemgr/sharemgr";
import {
  listUser
} from "@/api/system/user";
import axios from 'axios'
import { Message } from 'element-ui'
import { saveAs } from 'file-saver'
import { getToken } from '@/utils/auth'
import errorCode from '@/utils/errorCode'
import { blobValidate } from "@/utils/ruoyi";
export default {
  name: "Sharemgr",
  dicts: ["share_type", "apply_status", "time_limit"],
  computed: {
    userId: {
      get() {
        return this.$store.state.user.id
      }
    }
  },
  data() {
    return {
      api: process.env.VUE_APP_BASE_API,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 分享管理表格数据
      sharemgrList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        fileId: null,
        deadline: null,
        type: null,
        userId: null,
        shareUserId: null,
        userName: null,
        shareUserName: null,
        timeType: null,
        status: null,
        applyUserId: null,
        applyUserName: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        deadline: [{ required: true, message: "时限不能为空", trigger: "blur" }],
        type: [{ required: true, message: "分享类型不能为空", trigger: "blur" }],
        timeType: [{ required: true, message: "时长类型不能为空", trigger: "blur" }],
        userId: [{ required: true, message: "分享谁不能为空", trigger: "blur" }],
        applyUserId: [{ required: true, message: "审批人不能为空", trigger: "blur" }],
        status: [{ required: true, message: "审批状态不能为空", trigger: "blur" }],
      },
    };
  },
  created() {
    this.getList();
  },
  methods: {
    getDict(d) {
      return d.filter(v => v.value != 4)
    },
    /** 查询分享管理列表 */
    getList() {
      this.loading = true;
      listSharemgr({
        ...this.queryParams,
        applyUserId: this.userId
      }).then((response) => {
        this.sharemgrList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        fileId: null,
        deadline: null,
        type: null,
        userId: null,
        shareUserId: null,
        userName: null,
        shareUserName: null,
        timeType: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null,
        status: null,
        applyUserId: null,
        applyUserName: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加分享管理";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getSharemgr(id).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = "修改分享管理";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.id != null) {
            updateSharemgr(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addSharemgr(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm('是否确认删除分享管理编号为"' + ids + '"的数据项？')
        .then(function () {
          return delSharemgr(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "filemgr/sharemgr/export",
        {
          ...this.queryParams,
        },
        `sharemgr_${new Date().getTime()}.xlsx`
      );
    },
    async printErrMsg(data) {
      const resText = await data.text();
      const rspObj = JSON.parse(resText);
      const errMsg = errorCode[rspObj.code] || rspObj.msg || errorCode['default']
      Message.error(errMsg);
    },
    resource(name) {
      var url = process.env.VUE_APP_BASE_API + "/common/download?fileName=" + name;
      axios({
        method: 'get',
        url: url,
        responseType: 'blob',
        headers: { 'Authorization': 'Bearer ' + getToken() }
      }).then((res) => {
        console.log(res)
        const isBlob = blobValidate(res.data);
        if (isBlob) {
          const blob = new Blob([res.data])
          saveAs(blob, decodeURIComponent(res.headers['download-filename']))
        } else {
          this.printErrMsg(res.data);
        }
      })
    },
  },
};
</script>
